package com.training.security;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;

import com.training.dao.DAO;
import com.training.dao.SessMod;
import com.training.dao.UserDAO;
import com.training.model.EditUser;
import com.training.model.NewUser;

//import org.springframework.web.servlet.mvc.SimpleFormController;
@Controller
@RequestMapping("/registration.htm")
public class Registration {
	private static final Logger logger = LoggerFactory.getLogger(Registration.class);

	public Registration() {
	}

	EditUserValidator userValidator;

	@Autowired
	public Registration(EditUserValidator userValidator) {
		this.userValidator = userValidator;
	}

	@RequestMapping(method = RequestMethod.POST)
	public String processSubmit(@ModelAttribute("newUserForm") NewUser user,
			BindingResult result, SessionStatus status) {

		userValidator.validate(user, result);

		if (result.hasErrors()) {
			// if validator failed
			return "NewUserForm";
		} else {
			status.setComplete();
			//DAO.getUser().newUser();
			UserDAO u = new UserDAO(user.getName(), user.getPassword(), user.getMail());
			u.newUser();
			//System.out.println("isInTable: "+u.isUserName("root"));
			
			// form success
			return "NewUserSuccess";
		}
	}

	@RequestMapping(method = RequestMethod.GET)
	public String initForm(ModelMap model) {
		NewUser user = new NewUser();
		// command object
		model.addAttribute("newUserForm", user);
		// return form view
		return "NewUserForm";
	}

//	@ModelAttribute("webFrameworkList")
//	public List<String> populateWebFrameworkList() {
//
//		// Data referencing for web framework checkboxes
//		List<String> webFrameworkList = new ArrayList<String>();
//		webFrameworkList.add("Spring MVC");
//		webFrameworkList.add("Struts 1");
//		webFrameworkList.add("Struts 2");
//		webFrameworkList.add("JSF");
//		webFrameworkList.add("Apache Wicket");
//
//		return webFrameworkList;
//	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
}
